import {useRef, useState, useEffect} from 'react'
import elementResizeDetectorMaker from 'element-resize-detector'
import {fromEventPattern} from 'rxjs'

export const erd = elementResizeDetectorMaker();

interface Args {

}

type DomRect = {width: number | string; height: number | string}

export default <T extends HTMLElement>(config: Args): [React.RefObject<T>, DomRect] => {
  const element = useRef<T>(null)
  const [domRect, setDomRect] = useState<DomRect>({width: '100%', height: '100%'})

  useEffect(() => {
    const ele = element.current as HTMLElement

    const resize = () => {
      const {width, height} = ele.getBoundingClientRect()

      setDomRect({width, height})
    }

    const resizeHanlde$ = fromEventPattern(
      hanlde => erd.listenTo(ele, hanlde),
      hanlde => erd.removeListener(ele, hanlde)
    )

    const resizeHanlde = resizeHanlde$.subscribe(resize)

    return () => {
      resizeHanlde.unsubscribe()
    }
  }, [])

  return [element, domRect]
}
